﻿
using Microsoft.AspNetCore.Http.Connections;

namespace Timo.SqlSugar.DbContext;

public static class DbContextSetup
{
    public static void AddSugarDbContext<T>(this IServiceCollection services, IConfiguration configuration, ConnectionConfig connectionOption, bool enableSqlLog) where T : DbContextBase
    {
        services.AddScoped<T>();
        var name = typeof(T).Name;
        var options = services.AddOptions<ConnectionConfig>(name);
        services.Configure<ConnectionConfig>(name, op =>
        {
            //op = connectionOption;
            op.ConfigId = connectionOption.ConfigId;
            op.ConnectionString = connectionOption.ConnectionString;
            op.DbType = connectionOption.DbType;
            op.IsAutoCloseConnection = connectionOption.IsAutoCloseConnection;
            if (enableSqlLog)
            {
                op.AopEvents = new AopEvents
                {
                    OnLogExecuting = (sql, pars) =>
                    {
                        Console.WriteLine(DateTime.Now);
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine($"{string.Join(", ", pars?.Select(it => it.ParameterName + "=" + it.Value))}");
                        Console.WriteLine(sql);
                        Console.ResetColor();
                    }
                };
            }
        });
    }
    public static void AddSugarMultipleDbContext<T>(this IServiceCollection services, IConfiguration configuration, bool enableSqlLog, params (Type dbContextType, ConnectionConfig connectionOption)[] dbs) where T : class
    {
        services.AddScoped<T>();
        var name = typeof(T).Name;
        var options = services.AddOptions<List<ConnectionConfig>>(name);
        services.Configure<List<ConnectionConfig>>(name, ops =>
        {
            foreach (var item in dbs)
            {
                var op = item.connectionOption;
                if (enableSqlLog)
                {
                    op.AopEvents = new AopEvents
                    {
                        OnLogExecuting = (sql, pars) =>
                        {
                            Console.WriteLine(DateTime.Now);
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine($"{string.Join(", ", pars?.Select(it => it.ParameterName + "=" + it.Value))}");
                            Console.WriteLine(sql);
                            Console.ResetColor();
                        }
                    };
                }
                ops.Add(op);
            }
        });
    }
}
